#include "../../include/utils/log_audit.h"
#include <sqlite3.h>
#include <time.h>
#include "../../include/utils/sm3.h"
#include <string.h>

void log_action(sqlite3 *db, int user_id, const char *action, const char *file_path, const char *prev_hash)
{
    time_t now = time(NULL);
    char timestamp[20];
    strftime(timestamp, 20, "%Y-%m-%d %H:%M:%S", localtime(&now));
    
    unsigned char current_hash[SM3_DIGEST_LENGTH];
    sm3((const unsigned char *)prev_hash, strlen(prev_hash), current_hash);
    
    char hex_hash[SM3_DIGEST_LENGTH * 2 + 1];
    for (int i = 0; i < SM3_DIGEST_LENGTH; i++)
    {
        sprintf(hex_hash + i * 2, "%02x", current_hash[i]);
    }
    hex_hash[SM3_DIGEST_LENGTH * 2] = 0;

    sqlite3_stmt *stmt;
    const char *sql = "INSERT INTO audit_logs (timestamp, user_id, action, file_path, prev_hash, current_hash) "
                      "VALUES (?, ?, ?, ?, ?, ?);";
    
    sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
    sqlite3_bind_text(stmt, 1, timestamp, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 2, user_id);
    sqlite3_bind_text(stmt, 3, action, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 4, file_path, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 5, prev_hash, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 6, hex_hash, -1, SQLITE_STATIC);
    
    sqlite3_step(stmt);
    sqlite3_finalize(stmt);
}

// 简化版日志函数，用于不需要数据库的场景
void calculate_log_hash(const char *prev_hash, const char *action, const char *timestamp, char *current_hash)
{
    // 拼接动作和时间戳
    char log_entry[512];
    snprintf(log_entry, sizeof(log_entry), "%s|%s|%s", prev_hash, action, timestamp);

    // 计算SM3哈希作为当前日志链哈希值
    sm3((const unsigned char *)prev_hash, strlen(prev_hash), (unsigned char *)current_hash);
}